package com.example.demo.photoFile.util;

import com.example.demo.photoFile.RadarChartLayers;
import org.apache.commons.lang.StringUtils;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.category.DefaultCategoryDataset;

import java.awt.*;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import static org.jfree.chart.JFreeChart.DEFAULT_TITLE_FONT;

public class RadarChartUtil {

    //六边
    private static final int weight = 1200;
    private static final int height = 1000;

    //三角
    private static final int weight2 = 1000;
    private static final int height2 = 800;


    /**
     * 保存雷达图文件
     *
     * @param url    雷达图存放地址
     * @param layers 最高得分
     * @param code   分支各项名称
     * @param user   score各项得分
     * @param termid 学期
     * @param pid    画像id
     * @param code2  图片编号
     * @return
     */
    public static String saveAsFile(String url, int layers, List<String> code, List<RadarChartLayers> user, Long termid,
                                    Long pid, int code2) {
        FileOutputStream out = null;
        try {
            // 学期-学生id-编号.png
            url = url + File.separator + termid + File.separator + pid + File.separator + code2 + ".png";
            File outFile = new File(url);
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }
            out = new FileOutputStream(url);
            // 保存为PNG
            if (code != null && code.size() == 6) {
                ChartUtilities.writeChartAsPNG(out, createChart(layers, code, user), weight, height);
            } else {
                ChartUtilities.writeChartAsPNG(out, createChart(layers, code, user), weight2, height2);
            }
            out.flush();
            return url;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // do nothing
                }
            }
        }
        return null;
    }

    /**
     * 创建雷达图
     *
     * @param layers 最高得分
     * @param code   分支各项名称
     * @param user   score各项得分
     * @return
     */
    public static JFreeChart createChart(int layers, List<String> code, List<RadarChartLayers> user) {
        //SpiderWebPlot是Jfreechart自带的
        // 不用Jfreechart自带的SpiderWebPlot，继承SpiderWebPlot重写MySpiderWebPlot
        CalibrationSpiderWebPlot spiderwebplot = new CalibrationSpiderWebPlot(createRadarChart(layers, code, user), 3,
                true);
        // 边框颜色
        spiderwebplot.setOutlinePaint(new Color(0x0000000, true));
        // 设置内环颜色
        spiderwebplot.setSeriesPaint(0, Color.RED);
        // 设置外环颜色
        spiderwebplot.setSeriesPaint(1, Color.green);
        // 设置扇形分隔线颜色
        spiderwebplot.setAxisLinePaint(Color.black);
        // 设置刻度线前缀
        spiderwebplot.setLablePrefix("len-");
        //设置标签颜色
        try {
            spiderwebplot.setLabelFont(setFont());
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 设置刻度线以及大类名称颜色
        spiderwebplot.setLabelPaint(Color.black);
        JFreeChart jfreechart = null;
        jfreechart = new JFreeChart(null, DEFAULT_TITLE_FONT, spiderwebplot, false);
        //设置图表的边框可见性为真
        jfreechart.setBorderVisible(false);
        //设置图表背景颜色
        jfreechart.setBackgroundPaint(Color.white);
        //控制图片的透明度
        jfreechart.setBackgroundImageAlpha(0.0f);
        return jfreechart;
    }


    /**
     * 生成雷达图数据
     *
     * @param layers 最高得分
     * @param code   分支各项名称
     * @param user   score各项得分
     * @return
     */
    public static DefaultCategoryDataset createRadarChart(int layers, List<String> code, List<RadarChartLayers> user) {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        for (int j = 1; j <= layers; j++) {
            for (int i = 0; i < code.size(); i++) {
                dataset.addValue(j, String.valueOf(j), code.get(i));
            }
        }
        if (user != null && user.size() > 0) {
            for (int i = 0; i < user.size(); i++) {
                dataset.addValue(user.get(i).getScore(), String.valueOf(code.size() + 1), user.get(i).getCode());
            }
        }
        return dataset;
    }

    /**
     * 判断该程序是不是jar启动方式
     *
     * @return
     */
    public static boolean isStartupFromJar() {
        try {
            Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources("");
            if (resources.hasMoreElements()) {
                URL url = resources.nextElement();
                return StringUtils.equalsIgnoreCase(url.getProtocol(), "jar");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return false;
    }


    /**
     * 设置字体
     */
    private static Font setFont() throws Exception {
        Font font;
        if (isStartupFromJar()) {
            //因为本地ide加载resource/font资源的方式与jar启动加载资源的方式不一样，所以这里判断一下是以什么方式加载的
            font = Font.createFont(Font.TRUETYPE_FONT, RadarChartUtil.class.getClassLoader().getResourceAsStream("/fonts/simhei.ttf")).deriveFont(Font.PLAIN, 30f);
        } else {
            font = Font.createFont(Font.TRUETYPE_FONT, new File("src\\main\\resources\\fonts\\simhei.ttf")).deriveFont(Font.BOLD, 30f);
        }
        GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(font);
        return font;
    }

}
